import { useLocation, useNavigate } from "react-router-dom";
import useGetUserInfo from "./useGetUserInfo";
import { useEffect } from "react";

import {
  isLoginOrRegister,
  isNONeedUserInfo,
  LOGIN_PATHNAME,
  MANAGE_INDEX_PATHNAME,
} from "../router";
import { getToken, getCustom, setCustom } from "../utils/user-token";

export const useNavPage = (waitingUserData: boolean) => {
  const { pathname } = useLocation();

  const { username } = useGetUserInfo();
  const navigate = useNavigate();

  useEffect(() => {
    // 在路由变化时持久化存储路径
    if (!isLoginOrRegister(pathname)) {
      setCustom("REDIRECT_PATH", pathname);
    }
    console.log("当前路径:", pathname);
    console.log("是否需要用户信息:", !isNONeedUserInfo(pathname));
    console.log("用户状态:", username ? "已登录" : "未登录");
    if (!waitingUserData) return;
    const token = getToken();

    if (!token && isNONeedUserInfo(pathname)) return;
    //如果有用户信息，并且不是登录页，则跳转到首页
    // console.log("username：测试", username);
    if (username && token) {
      if (isLoginOrRegister(pathname)) {
        const redirectPath =
          getCustom("REDIRECT_PATH") || MANAGE_INDEX_PATHNAME;
        navigate(redirectPath);
        setCustom("REDIRECT_PATH", ""); // 清除存储
        // navigate( redirectPath || MANAGE_INDEX_PATHNAME);
      }
      return;
    }
    //如果未登录
    if (username || token || isNONeedUserInfo(pathname)) {
      return;
    } else {
      navigate(LOGIN_PATHNAME);
    }
  }, [pathname, username, waitingUserData, navigate]);
};
